<?php

namespace app\wechat\controller\api;

use app\wechat\service\WechatService;
use think\admin\Controller;
use app\data\model\DataUser;

/**
 * 微信扫码授权登录
 * Class Login
 * @package app\wechat\controller\api
 */
class Login extends Controller
{
  // 授权登陆
    public function login()
    {
        if ($this->request->isPost()) {
            
            $code = $this->request->post('code', '');

            if (!$code) {
                $this->error('临时授权失败');
            }
            
            //调用微信接口
            $result = $this->code2ession($code);
            
            $openid = isset($result['openid']) ? $result['openid'] : '';

            if (empty($openid)) {
                $this->error('微信授权失败');
            }

            //根据openid判断是否有绑定用户,有绑定用户就将用户信息返回,没绑定就提示绑定
            $User = DataUser::where(['openid1' => $openid])->find();
            
            if ($User) {

                // $data = [
                //     'id' => $User['id'],
                //     'openid' => $User['openid'],
                //     'email' => $User['email'],
                //     'nickname' => $User['nickname'],
                //     'avatar' => $User['avatar_cdn'],
                //     'sex' => $User['sex'],
                //     'sex_text' => $User['sex_text'],
                //     'province' => $User['province'],
                //     'city' => $User['city'],
                //     'district' => $User['district'],
                //     'createtime' => $User['createtime'],
                //     'content' => $User['content'],
                //     'point' => $User['point'],
                //     'vip' => $User['vip'],
                //     'auth' => $User['auth'],
                //     'cover' => $User['cover_cdn'],
                //     'region' => explode('-', $User['region']),
                //     'region_text' => $User['region']
                // ];

                $this->success('登录成功', $User,1);
            } else {
                $this->success('请先关联账号', '/pages/public/login', null);
            }
        }
    }

    // 微信服务端发送GET请求
    public function code2ession($js_code = null)
    {
        if ($js_code) {

            $appid = 'wx66046d4032de04d9';

            // AppSecret(小程序密钥)	
            $appSecret = '5f269a52844b96532a4a07088901b146';

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$js_code&grant_type=authorization_code";

            //发起get请求
            $result = $this->https_request($url);

            //获取结果 将json转化为数组
            $resultArr = json_decode($result, true);

            return $resultArr;
        } else {
            $this->error('发送GET请求失败');
        }
    }

    //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    // https://www.php.net/manual/zh/book.curl.php
    protected function https_request($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            // 发送会话，返回结果
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            $this->error('curl扩展返回失败');
        }
    }
    
    


    /**
     * 数据缓存时间
     * @var integer
     */
    protected $expire = 3600;

    /**
     * 授权码前缀
     * @var string
     */
    protected $prefix = 'wxlogin';

    /**
     * 扫描显示二维码
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
     * @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     * @throws \think\exception\HttpResponseException
     */
    public function qrc()
    {
        $mode = intval(input('mode', '0'));
        $code = $this->prefix . md5(uniqid('t', true) . rand(10000, 99999));
        $text = url('wechat/api.login/oauth', [], false, true) . "?code={$code}&mode={$mode}";
        // 生成二维码并返回结果
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($text)->setSize(300)->setPadding(20);
        $content = base64_encode($qrcode->setImageType('png')->get());
        $this->success('获取二维码成功', ['code' => $code, 'image' => "data:image/png;base64,{$content}"]);
    }

    /**
     * 微信授权结果处理
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function oauth()
    {
        $this->code = input('code', '');
        $this->mode = input('mode', '0');
        if (stripos($this->code, $this->prefix) === 0) {
            $this->url = $this->request->url(true);
            $this->fans = WechatService::instance()->getWebOauthInfo($this->url, $this->mode);
            if (is_array($this->fans) && isset($this->fans['openid'])) {
                $this->fans['token'] = md5(uniqid('t', true) . rand(10000, 99999));
                $this->app->cache->set("wxlogin{$this->code}", $this->fans, $this->expire);
                $this->app->cache->set($this->fans['openid'], $this->fans['token'], $this->expire);
                $this->message = '授权成功';
                $this->fetch('success');
            } else {
                $this->message = '授权失败';
                $this->fetch('failed');
            }
        } else {
            $this->message = '授权失败';
            $this->fetch('failed');
        }
    }

    /**
     * 获取授权信息
     * 用定时器请求这个接口
     * @throws \think\exception\HttpResponseException
     */
    public function query()
    {
        $this->code = input('code', '');
        if (stripos($this->code, $this->prefix) === 0) {
            $this->ckey = "wxlogin{$this->code}";
            $this->fans = $this->app->cache->get($this->ckey, new \stdClass());
            $this->success('获取授权信息', $this->fans);
        } else {
            $this->error("授权CODE不能为空！");
        }
    }
}